package com.sky.server.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.sky.bo.WeiXinLogin;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.SqlException;
import com.sky.mapper.UserMapper;
import com.sky.server.UserServer;
import com.sky.vo.UserLoginVO;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
@Service
public class UserServerImpl implements UserServer {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        // 根据前端传来的登录码
        HashMap<String, String> paras = new HashMap<>();
        paras.put("appid", "wxcd38079dc0f056db");
        paras.put("secret", "b656ee61de755a6a09699067c833b33c");
        paras.put("js_code", userLoginDTO.getCode());
        paras.put("grant_type", "authorization_code");
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String str = HttpClientUtil.doGet(url, paras);


        // 获取微信发来的数据，根据optionid查数据库是否有用户
        WeiXinLogin weiXinLogin = null;
        try {
            weiXinLogin = JSONUtil.toBean(str, WeiXinLogin.class);
            log.info("向微信获取optenid失败");
        } catch (Exception e) {
            throw new RuntimeException("登录失败");
        }
        log.info("openid:{}", weiXinLogin.getOpenid());
        User userOne = userMapper.getByOptionid(weiXinLogin.getOpenid());
        // 如果没有用户就创建用户
        if (userOne==null) {
            User user = new User();
            user.setId(System.currentTimeMillis());
            user.setName("土鸡瓦狗");
            user.setOpenid(weiXinLogin.getOpenid());
            user.setCreateTime(LocalDateTime.now());
            userOne = user;
            try {
                userMapper.addUser(user);
            } catch (Exception e) {
                log.info("用户没有插入成功");
                throw new SqlException("创建用户失败，请稍后再试");
            }
        }

        // 用户存在生成jwt返回
        StpUtil.login(userOne.getId());
        String token = StpUtil.getTokenValue();
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setToken(token);
        userLoginVO.setId(userOne.getId());

        return userLoginVO;
    }
}
